<template>
  <div>
    <div class="mt50 mb35 textCenter imgBox">
      <img class="avatar" :src="user.userInfo?.avatar ? handleImgSrc(user.userInfo?.avatar) : defaultAvatar" alt="" />
      <div class="upload">
        <van-icon name="photo-o" size="24px" @click="handleUpload" />
      </div>
    </div>

    <van-cell-group>
      <van-cell title="账号" :value="user.userInfo?.account" />
      <van-cell title="昵称" is-link :value="user.userInfo?.nickname" @click="showPopup = true" />
      <van-cell title="邮箱" is-link :value="user.userInfo?.email" @click="showEmailPopup = true" />
      <van-cell title="密码" is-link value="********" @click="showPasPopup = true" />
    </van-cell-group>

    <van-popup v-model:show="showPopup" position="bottom" :style="{ height: '30%' }" closeable
      :close-on-click-overlay="false" @open="openPopup" @click-close-icon="closePopup">
      <div class="mt100">
        <van-cell-group inset>
          <van-field v-model="otherData.nickname" label="昵称" placeholder="请输入昵称" />
        </van-cell-group>
        <div class="mt30 ml30 mr30">
          <van-button type="primary" block @click="submit">保存</van-button>
        </div>
      </div>
    </van-popup>

    <van-popup v-model:show="showEmailPopup" position="bottom" :style="{ height: '35%' }" closeable
      :close-on-click-overlay="false" @click-close-icon="closeEmailPopup">
      <div class="mt100 emailBox">
        <van-cell-group inset>
          <van-field v-model="emailData.email" label="邮箱" placeholder="请输入邮箱" />
        </van-cell-group>
        <van-cell-group inset>
          <van-field v-model="emailData.code" center clearable label="验证码" placeholder="请输入邮箱验证码"
            :rules="[{ required: true, message: '请填写邮箱验证码' }, { validator: codeRules }]">
            <template #button>
              <van-button size="small" type="primary" :disabled="codeInfo.isCodeSent" @click="sendCode">{{
                codeInfo.timer ? `${codeInfo.codeTime}秒` : '获取验证码' }}</van-button>
            </template>
          </van-field>
        </van-cell-group>
        <div class="mt30 ml30 mr30">
          <van-button type="primary" block @click="emailSubmit">保存</van-button>
        </div>
      </div>
    </van-popup>

    <van-popup v-model:show="showPasPopup" position="bottom" :style="{ height: '40%' }" closeable
      :close-on-click-overlay="false" @click-close-icon="closePasPopup">
      <div class="mt100">
        <van-cell-group inset>
          <van-field v-model="passData.oldPass" label="旧密码" placeholder="请输入旧密码" />
        </van-cell-group>
        <van-cell-group inset>
          <van-field v-model="passData.newPass" label="新密码" placeholder="请输入新密码" />
        </van-cell-group>
        <van-cell-group inset>
          <van-field v-model="passData.confirmPass" label="确认密码" placeholder="请输入确认密码" />
        </van-cell-group>
        <div class="mt30 ml30 mr30">
          <van-button type="primary" block @click="pasSubmit">保存</van-button>
        </div>
      </div>
    </van-popup>

    <Upload :showPopup.sync="showUpload" v-if="showUpload" @update:showPopup="handleUploadClose" />
  </div>
</template>

<script lang="ts" setup>
import { onBeforeUnmount, reactive, ref } from 'vue'
import { debounce, handleImgSrc } from '@/utils'
import { userStore } from '@/store'
import { FieldRuleValidator, showToast } from 'vant'
import { changePass, profileModify, updateEmail } from '@/api/user'
import regConfig from '@/config/reg.config'
import router from '@/router'
import Upload from './components/upload.vue'
import { updatePassType } from '@/types/userTypes'
import { sendEmailCode } from '@/api/common'
import defaultAvatar from '@/assets/images/avatar.jpg'
const showPopup = ref(false)
const showPasPopup = ref(false)
const showUpload = ref(false)
const showEmailPopup = ref(false)
const user = userStore()
const otherData = reactive({
  nickname: ''
})

const emailData = reactive({
  email: '',
  code: ''
})
const codeInfo = reactive({
  codeTime: 60,
  isCodeSent: false,
  timer: 0
})

const passData: updatePassType = reactive({
  oldPass: '',
  newPass: '',
  confirmPass: ''
})

const openPopup = () => {
  otherData.nickname = user.userInfo?.nickname || ''
}

const closePopup = () => {
  showPopup.value = false
  otherData.nickname = ''
}

const closeEmailPopup = () => {
  showEmailPopup.value = false
}

const closePasPopup = () => {
  showPasPopup.value = false
  passData.oldPass = ''
  passData.newPass = ''
  passData.confirmPass = ''
}

const codeRules: FieldRuleValidator = (val: number) => {
  if (!/^\d{6}$/.test(val.toString())) {
    return '请输入正确的验证码'
  }
  return true
}

const sendCode = debounce(async () => {
  if (!emailData.email) return showToast('请输入邮箱')
  if (!regConfig.email.test(emailData.email)) return showToast('邮箱格式错误')
  codeInfo.isCodeSent = true

  try {
    const { data } = await sendEmailCode({ email: emailData.email })
    if (data.code === 0) {
      showToast('邮箱验证码已发送')
      codeInfo.codeTime = 60
      codeInfo.timer = window.setInterval(() => {
        codeInfo.codeTime--
        if (codeInfo.codeTime < 1) {
          window.clearInterval(codeInfo.timer)
          codeInfo.timer = 0
          codeInfo.codeTime = 60
          codeInfo.isCodeSent = false
        }
      }, 1000)
    } else {
      showToast(data.msg || '邮箱验证码发送失败')
      codeInfo.isCodeSent = false
    }
  } catch (err) {
    showToast(err || '邮箱验证码发送失败')
    codeInfo.isCodeSent = false
  }
}, 1000, true)

const emailSubmit = async () => {
  if (!emailData.code) return showToast('请输入邮箱验证码')
  const { data } = await updateEmail(emailData)
  if (data.code === 0) {
    showToast('已修改')
    closeEmailPopup()
    user.getUserInfo()
  } else {
    showToast(data.msg || '邮箱修改失败')
  }
}

const submit = async () => {
  if (otherData.nickname) {
    if (otherData.nickname.length < 2 || otherData.nickname.length > 10) return showToast("昵称长度为2-10位")
    if (!/^[a-zA-Z0-9\u4e00-\u9fa5]+$/.test(otherData.nickname)) return showToast("昵称只能包含字母、数字和中文")
  }
  if (!otherData.nickname) {
    return showPopup.value = false
  }

  const params = {
    ...otherData
  }
  const { data } = await profileModify(params)
  if (data.code === 0) {
    showToast('已修改')
    closePopup()
    user.getUserInfo()
  } else {
    showToast(data.msg)
  }
}

const pasSubmit = async () => {
  if (!passData.oldPass) return showToast('请输入旧密码')

  if (!passData.newPass) return showToast('请输入新密码')
  if (passData.newPass.length < 8 || passData.newPass.length > 20) return showToast('新密码长度为8-20位')
  if (!/(?=.*[A-Za-z])(?=.*\d)/.test(passData.newPass)) return showToast('新密码必须包含字母和数字')

  if (!passData.confirmPass) return showToast('请输入确认密码')
  if (passData.newPass !== passData.confirmPass) return showToast('两次输入密码不一致')

  if (passData.oldPass === passData.newPass) return showToast('新密码不能与旧密码相同')

  const { data } = await changePass(passData)
  if (data.code === 0) {
    setTimeout(() => {
      showToast('已修改，请重新登录')
      showPasPopup.value = false

      user.clearUserInfo()
      localStorage.removeItem('redirectAfterLogin')
      router.push('/login')
    }, 500)
  } else {
    showToast(data.msg)
  }
}

const handleUpload = () => {
  showUpload.value = true
}

const handleUploadClose = (val: boolean, flag = true) => {
  showUpload.value = val
  if (flag) {
    user.getUserInfo()
  }
}

onBeforeUnmount(() => {
  if (codeInfo.timer) clearInterval(codeInfo.timer)
})
</script>

<style lang="scss" scoped>
.imgBox {
  position: relative;

  .avatar {
    max-width: 120px;
    max-height: 150px;
    border-radius: 50%;
  }

  .upload {
    position: absolute;
    top: 60%;
    left: 58%;
  }
}

.van-popup {
  background: #F7F8FA;
}

.van-cell__title {
  width: 0 !important;
}

.van-button--primary {
  background: #40a9ff;
  border-color: #40a9ff;
}
</style>